package com.chhuang.ewcrm.controller;

import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.entity.SysMenu;
import com.chhuang.ewcrm.entity.SysRole;
import com.chhuang.ewcrm.entity.SysRoleMenu;
import com.chhuang.ewcrm.entity.SysUser;
import com.chhuang.ewcrm.service.SysRoleMenuService;
import com.chhuang.ewcrm.service.SysRoleService;
import com.chhuang.ewcrm.service.SysUserService;
import com.chhuang.ewcrm.vo.ResultBean;
import com.chhuang.ewcrm.vo.RoleMenuVo;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * (SysRole)表控制层
 *
 * @author chhuang
 * @since 2020-10-23 11:09:11
 */
@RestController
@RequestMapping("/service/sysRole")
public class SysRoleController {
    Logger logger = LoggerFactory.getLogger(SysRoleController.class);
    /**
     * 服务对象
     */
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysRoleMenuService sysRoleMenuService;
    @Resource
    private SysUserService sysUserService;

    /**
     * 获取所有角色
     *
     * @return 单条数据
     */
    @GetMapping("getAll")
    public ResultBean<List<SysRole>> getAll() {
        ResultBean<List<SysRole>> resultBean = new ResultBean<>();
        resultBean.setSuccess(true);
        resultBean.setData(this.sysRoleService.query(null, "role_id"));
        return resultBean;
    }

    /**
     * 删除角色
     * @param roleId
     * @return
     */
    @DeleteMapping("/removeOne/{roleId}")
    public ResultBean<?> removeOne(@PathVariable("roleId") String roleId){
        ResultBean<?> resultBean = new ResultBean<>();
        if(StringUtils.isNotEmpty(roleId)){
            resultBean.setSuccess(this.sysRoleService.deleteById(roleId));
            if(resultBean.isSuccess()) {//删除角色关联菜单
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(roleId);
                this.sysRoleMenuService.deleteByEntity(sysRoleMenu);
            }
        }else{
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 根据id列表批量删除
     * @param roleIds
     * @return
     */
    @PutMapping("/removeList")
    public ResultBean<?> removeList(@RequestBody List<String> roleIds){
        ResultBean<?> resultBean = new ResultBean<>();
        if(roleIds!=null && !roleIds.isEmpty()){
            resultBean.setSuccess(this.sysRoleService.deleteByIds(roleIds)>0);
            //删除角色关联菜单
            if(resultBean.isSuccess()){
                roleIds.forEach(roleId->{
                    SysRoleMenu sysRoleMenu = new SysRoleMenu();
                    sysRoleMenu.setRoleId(roleId);
                    this.sysRoleMenuService.deleteByEntity(sysRoleMenu);
                });
            }
        }else{
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 修改角色信息
     * @param sysRole
     * @return
     * @throws IOException
     */
    @PutMapping("/editOne")
    public ResultBean<SysRole> editOne(@RequestBody SysRole sysRole){
        ResultBean<SysRole> resultBean = new ResultBean<SysRole>();
        resultBean.setSuccess(false);
        if(sysRole!=null && StringUtils.isNotEmpty(sysRole.getRoleName())) {
            if (StringUtils.isEmpty(sysRole.getRoleId())) { //添加
                Date now = new Date();
                sysRole.setCreateTime(now);
                sysRole.setModifyTime(now);
                sysRole = this.sysRoleService.insert(sysRole);
                resultBean.setData(sysRole);
                resultBean.setSuccess(resultBean.getData()!=null);
            } else{ //修改
                SysRole role = sysRoleService.queryById(sysRole.getRoleId());
                if (role != null) {
                    role.setRoleName(sysRole.getRoleName());
                    role.setModifyTime(new Date());
                    sysRole = this.sysRoleService.update(role);
                    resultBean.setData(sysRole);
                    resultBean.setSuccess(resultBean.getData()!=null);
                    //修改用户表中角色名
                    if(resultBean.isSuccess()){
                        SysUser user = new SysUser();
                        user.setRoleId(sysRole.getRoleId());
                        List<SysUser> users = sysUserService.query(user);
                        if(users!=null && !users.isEmpty()) {
                            for(int i=0; i<users.size(); i++){
                                user = users.get(i);
                                user.setRoleName(sysRole.getRoleName());
                                users.set(i, user);
                            }
                            sysUserService.updateBatch(users);
                        }
                    }
                } else
                    resultBean.setMessage("没有找到角色");
            }
        } else
            resultBean.setMessage("参数不能为空");
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 修改角色菜单
     * @param roleMenuVo
     * @return
     */
    @PutMapping("/editRoleMenu")
    public ResultBean<?> editRoleMenu(@RequestBody RoleMenuVo roleMenuVo){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if(StringUtils.isNotEmpty(roleMenuVo.getRoleId())){
            SysRole role = sysRoleService.queryById(roleMenuVo.getRoleId());
            if(role!=null){
                //选择删除现有的关联
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(role.getRoleId());
                sysRoleMenuService.deleteByEntity(sysRoleMenu);
                resultBean.setSuccess(true);
                //添加新的关联
                if(roleMenuVo.getMenus()!=null && !roleMenuVo.getMenus().isEmpty()) {
                    List<SysRoleMenu> sysRoleMenus = new LinkedList<>();
                    for (SysMenu menu : roleMenuVo.getMenus()) {
                        sysRoleMenu = new SysRoleMenu();
                        sysRoleMenu.setRoleId(role.getRoleId());
                        sysRoleMenu.setMenuId(menu.getMenuId());
                        sysRoleMenu.setMenuName(menu.getMenuName());
                        sysRoleMenu.setMenuUrl(menu.getMenuUrl());
                        sysRoleMenu.setMenuOrder(menu.getMenuOrder());
                        sysRoleMenu.setParentMenuId(menu.getParentMenuId());
                        Date now = new Date();
                        sysRoleMenu.setModifyTime(now);
                        sysRoleMenu.setCreateTime(now);
                        sysRoleMenus.add(sysRoleMenu);
                    }
                    sysRoleMenuService.insertBatch(sysRoleMenus);
                }
            }else
                resultBean.setMessage("此角色不存在");
        }else
            resultBean.setMessage("参数不能为空");

        return resultBean;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param roleId 主键
     * @return 单条数据
     */
    @GetMapping("/getOne")
    public ResultBean<SysRole> getOne(String roleId) {
        ResultBean<SysRole> resultBean = new ResultBean<SysRole>();
        resultBean.setSuccess(false);
        if(StringUtils.isNotEmpty(roleId)){
            resultBean.setSuccess(true);
            resultBean.setData(this.sysRoleService.queryById(roleId));
        }else{
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    @PostMapping("/queryPage")
    public ResultBean<PageInfo<SysRole>> query(@RequestBody QueryBean<SysRole> queryBean){
        logger.debug(queryBean.toString());
        ResultBean<PageInfo<SysRole>> resultBean = new ResultBean<PageInfo<SysRole>>();

        PageInfo<SysRole> pageInfo = null;
        List<SysRole> roles = null;
        if(queryBean!=null) {
            if (StringUtils.isNotEmpty(queryBean.getOrderBy()))
                pageInfo = sysRoleService.search(queryBean.getSearch(), queryBean.getPageNum(), queryBean.getPageSize(), queryBean.getOrderBy());
            else
                pageInfo = sysRoleService.search(queryBean.getSearch(), queryBean.getPageNum(), queryBean.getPageSize());
            resultBean.setData(pageInfo);
            resultBean.setSuccess(true);
            resultBean.setCode(queryBean.getDraw());
        }else {
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }

        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 获取角色关联的菜单
     * @param roleId
     * @return
     */
    @GetMapping("/getRoleMenus")
    public ResultBean<List<SysRoleMenu>> getRoleMenus(String roleId){
        ResultBean<List<SysRoleMenu>> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if(StringUtils.isNotEmpty(roleId)) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            resultBean.setData(sysRoleMenuService.query(sysRoleMenu));
            resultBean.setSuccess(true);
        }else
            resultBean.setMessage("参数不为空");

        logger.debug(resultBean.toString());
        return resultBean;
    }
    
}